package org.common.utils.consumer;
import org.common.utils.thread.ThreadTool;
import org.common.utils.tool.StringTool;

import java.util.concurrent.Executor;
import java.util.function.BiConsumer;

/**
 * 消费者队列配置
 * @author zhouzhibing
 * @date 2025/8/6
 */
public class ConsumerConfig {
    /**
     * 消费功能名称
     */
    private String name;
    /**
     * 消费组，队列数量
     */
    private int count;
    /**
     * 消费处理，执行器.
     */
    private Executor executor;
    /**
     * 消费处理
     */
    private ConsumerHandler handler;

    private ConsumerConfig() {

    }

    public String getName() {
        return name;
    }

    public int getCount() {
        return count;
    }

    public Executor getExecutor() {
        return executor;
    }

    public ConsumerHandler getHandler() {
        return handler;
    }

    @Override
    public String toString() {
        return "ConsumerConfig{" +
                "name='" + name + '\'' +
                ", count=" + count +
                ", executor=" + executor +
                ", handler=" + handler +
                '}';
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public static class Builder {
        private final ConsumerConfig consumerConfig = new ConsumerConfig();

        public Builder setName(String name) {
            consumerConfig.name = name;
            return this;
        }

        public Builder setCount(int count) {
            consumerConfig.count = count;
            return this;
        }

        public Builder setExecutor(Executor executor) {
            consumerConfig.executor = executor;
            return this;
        }

        public Builder setHandler(ConsumerHandler handler) {
            consumerConfig.handler = handler;
            return this;
        }

        public ConsumerConfig build() {
            if(consumerConfig.executor == null) {
                consumerConfig.executor = ThreadTool.getDefaultExecutor();
            }

            if(consumerConfig.count <= 0) {
                consumerConfig.count = ThreadTool.getCpuCount();
            }

            if (StringTool.isEmpty(consumerConfig.name)) {
                throw new ConsumerException("ConsumerConfig.name is empty");
            }

            if(consumerConfig.handler == null) {
                throw new ConsumerException("ConsumerConfig.handler is null");
            }

            return consumerConfig;
        }
    }
}
